package com.dnw.adapter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.util.MultiTypeDelegate;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.dnw.listener.PermissionListener;
import com.dnw.modle.Funnys;
import com.dnw.modle.Program;
import com.dnw.shyfunny.ProgramDetailActivity;
import com.dnw.shyfunny.R;
import com.dnw.util.DoLikeOr;
import com.dnw.util.FileUtils;
import com.dnw.util.GlideUtils;
import com.dnw.util.PreUtils;
import com.dnw.util.ShareUtil;
import com.dnw.util.UIUtils;
import com.dnw.view.CircleProgressView;
import com.socks.library.KLog;
import com.sunfusheng.glideimageview.GlideImageLoader;
import com.sunfusheng.glideimageview.progress.OnGlideImageViewListener;
import com.sunfusheng.glideimageview.util.DisplayUtil;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author ChayChan
 * @description: TODO
 * @date 2017/7/6  17:10
 */

public class FunnysAdapter extends BaseQuickAdapter<Funnys, BaseViewHolder> {

    /**
     * 纯文字布局(文章、广告)
     */
    private static final int TEXT_NEWS              = 100;
    /**
     * 居中大图布局(1.单图文章；2.单图广告；3.视频，中间显示播放图标，右侧显示时长)
     */
    private static final int CENTER_SINGLE_PIC_NEWS = 200;
    /**
     * 右侧小图布局(1.小图新闻；2.视频类型，右下角显示视频时长)
     */
    private static final int CENTER_SINGLE_GIF_NEWS = 300;
    /**
     * 三张图片布局(文章、广告)
     */
    private static final int THREE_PICS_NEWS        = 400;
    /**
     * 视频列表类型
     */
    private static final int VIDEO_LIST_NEWS = 500;
    /**
     * 视频列表类型
     */
    private static final int PGOGRAM_LIST = 600;
    /**
     * 直播列表类型
     */
    private static final int LIVE_LIST = 700;


    private Context mContext;
    private String  mChannelCode;
    private boolean isVideoList;
    private List<Program>  mPrograms;

    private PermissionListener mPermissionListener;

    @Override
    public void setOnItemChildClickListener(OnItemChildClickListener listener) {
        super.setOnItemChildClickListener(listener);
    }

    public void setmPrograms(List<Program> mPrograms) {
        this.mPrograms = mPrograms;
    }

    /**
     * @param context     上下文
     * @param channelCode 频道
     * @param isVideoList 是否是视频列表
     * @param data        新闻集合
     */
    public FunnysAdapter(Context context, String channelCode, boolean isVideoList, List<Funnys> data, List<Program>  programs) {
        super(data);
        mContext = context;
        mChannelCode = channelCode;
        this.isVideoList = isVideoList;
        this.mPrograms = programs;
        //Step.1
        setMultiTypeDelegate(new MultiTypeDelegate<Funnys>() {

            @Override
            protected int getItemType(Funnys funnys) {

                //                if("" == funnys.smallImage || funnys.smallImage.isEmpty()){
                //                    return TEXT_NEWS;
                //                } else if (!funnys.smallImage.isEmpty()){
                //                    return CENTER_SINGLE_PIC_NEWS;
                //                }
                //
                //                return TEXT_NEWS;
                if (null != funnys.mediaType) {
                    switch (funnys.mediaType) {
                        case "TEXT":
                            return TEXT_NEWS;
                        case "IMAGE":
                            return CENTER_SINGLE_PIC_NEWS;
                        case "GIF":
                            return CENTER_SINGLE_GIF_NEWS;
                        case "LIVE":
                            return LIVE_LIST;
                        case "PROGRAM":
                            return PGOGRAM_LIST;
                    }
                }
                return TEXT_NEWS;
            }
        });
        //Step .2
        getMultiTypeDelegate()
                .registerItemType(TEXT_NEWS, R.layout.item_text_funnys)//纯文字布局
                .registerItemType(CENTER_SINGLE_PIC_NEWS, R.layout.item_center_pic_funnys)//居中大图布局
                .registerItemType(CENTER_SINGLE_GIF_NEWS, R.layout.item_center_gif_funnys)//右侧小图布局
                .registerItemType(THREE_PICS_NEWS, R.layout.item_three_pics_news)//三张图片布局
                .registerItemType(VIDEO_LIST_NEWS, R.layout.item_video_list)//三张图片布局
                .registerItemType(PGOGRAM_LIST, R.layout.item_program)//广告
                .registerItemType(LIVE_LIST,R.layout.item_live_funnys);//直播

    }


    @Override
    protected void convert(BaseViewHolder helper, Funnys funnys) {
        //设置标题、底部作者、评论数、发表时间
        //        if (!isVideoList) {
        //            //如果不是视频列表
        //            helper.setText(R.id.tv_title, funnys.content)
        //                    .setText(R.id.tv_author, funnys.source);
        //        }
        //根据类型为不同布局的条目设置数据
        switch (helper.getItemViewType()) {
            case TEXT_NEWS:
                //三张图片的新闻
                helper.setText(R.id.tv_title, funnys.content)
                        .setText(R.id.tv_xd_good, funnys.good)
                        .setText(R.id.tv_xd_bad, funnys.bad)
                        .setText(R.id.tv_xd_share, funnys.shareCount)
                        .setText(R.id.tv_xd_user, funnys.loginName)
                        .setText(R.id.tv_xd_time, funnys.createTime);
                GlideUtils.loadRound(mContext, funnys.avatarImg, helper.getView(R.id.iv_xd_user));
                doAction(helper, funnys, funnys.mediaType);
                break;
            case LIVE_LIST:
                Toast.makeText(mContext, "进入", Toast.LENGTH_SHORT).show();
                //直播UI加载
                doAction(helper, funnys, funnys.mediaType);
                break;
            case CENTER_SINGLE_PIC_NEWS:
                //三张图片的新闻
                helper.setText(R.id.tv_title, funnys.content)
                        .setText(R.id.tv_xd_good, funnys.good)
                        .setText(R.id.tv_xd_bad, funnys.bad)
                        .setText(R.id.tv_xd_share, funnys.shareCount)
                        .setText(R.id.tv_xd_user, funnys.loginName)
                        .setText(R.id.tv_xd_time, funnys.createTime);
                GlideUtils.load(mContext, funnys.bigImage, helper.getView(R.id.iv_img));
                GlideUtils.loadRound(mContext, funnys.avatarImg, helper.getView(R.id.iv_xd_user));
                doAction(helper, funnys, funnys.mediaType);
                break;
            case CENTER_SINGLE_GIF_NEWS:
                //三张图片的新闻
                helper.setText(R.id.tv_title, funnys.content)
                        .setText(R.id.tv_xd_good, funnys.good)
                        .setText(R.id.tv_xd_bad, funnys.bad)
                        .setText(R.id.tv_xd_share, funnys.shareCount)
                        .setText(R.id.tv_xd_user, funnys.loginName)
                        .setText(R.id.tv_xd_time, funnys.createTime);
                //                GlideUtils.loadGif(mContext, funnys.bigImage, helper.getView(R.id.iv_img));
                GlideUtils.load(mContext, funnys.smallImage, helper.getView(R.id.iv_img));
                //                ivPlay.setVisibility(View.GONE);
                //                loadGifa(mContext, funnys.bigImage, helper.getView(R.id.iv_img));
                GlideUtils.loadRound(mContext, funnys.avatarImg, helper.getView(R.id.iv_xd_user));
                doAction(helper, funnys, funnys.mediaType);
                break;
            case PGOGRAM_LIST:
                Random random=new Random();
                Integer a = random.nextInt(mPrograms.size());
                Program program = mPrograms.get(a);

                helper.setText(R.id.tv_name, program.name)
                        .setText(R.id.tv_info, program.score + "分  " + program.downloadCount + "人下载     " + program.size)
                        .setText(R.id.tv_slogan, program.slogan);
                //                GlideUtils.loadGif(mContext, funnys.bigImage, helper.getView(R.id.iv_img));
                GlideUtils.load(mContext, program.iconDownloadUrl, helper.getView(R.id.iv_icon));
                doProgram(helper, program);
                break;

        }
    }
    private void doProgram(final BaseViewHolder helper, final Program program) {
        Button bt_download = helper.getView(R.id.bt_download);
        bt_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ProgramDetailActivity.class);
                intent.putExtra("program", program);
                mContext.startActivity(intent);
            }
        });
    }
    private void doAction(final BaseViewHolder helper, final Funnys funnys, String mediaType) {
        LinearLayout lyDoGood = helper.getView(R.id.ly_do_good);
        LinearLayout lyDoBad = helper.getView(R.id.ly_do_bad);
        LinearLayout lyDoShare = helper.getView(R.id.ly_do_share);

        lyDoGood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (PreUtils.getBoolean(funnys.id + "good", false)) {
                    UIUtils.showToast(mContext.getResources().getString(R.string.do_good_already));
                    return;
                }

                DoLikeOr doLikeOr = new DoLikeOr() {
                    @Override
                    public void onSuccess(String msg) {
                        helper.setText(R.id.tv_xd_good, Integer.parseInt(funnys.good) + 1 + "");
                        PreUtils.putBoolean(funnys.id + "good", true);
                        UIUtils.showToast(mContext.getResources().getString(R.string.do_good_success));
                    }

                    @Override
                    public void onDecodeError() {
                        UIUtils.showToast(mContext.getResources().getString(R.string.do_good_failed));
                    }
                };
                doLikeOr.sendRequest(funnys.id, funnys.userId, "LIKE");
            }
        });
        lyDoBad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (PreUtils.getBoolean(funnys.id + "bad", false)) {
                    UIUtils.showToast(mContext.getResources().getString(R.string.do_bad_already));
                    return;
                }
                DoLikeOr doLikeOr = new DoLikeOr() {
                    @Override
                    public void onSuccess(String msg) {
                        helper.setText(R.id.tv_xd_bad, Integer.parseInt(funnys.bad) + 1 + "");
                        PreUtils.putBoolean(funnys.id + "bad", true);
                        UIUtils.showToast(mContext.getResources().getString(R.string.do_bad_success));
                    }

                    @Override
                    public void onDecodeError() {
                        UIUtils.showToast(mContext.getResources().getString(R.string.do_bad_failed));
                    }
                };
                doLikeOr.sendRequest(funnys.id, funnys.userId, "UNLIKE");
            }
        });
        lyDoShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (PreUtils.getBoolean(funnys.id + "share", false)) {
                    UIUtils.showToast(mContext.getResources().getString(R.string.do_share_already));
                    return;
                }
                                ShareUtil.share(mContext, funnys);
                //                new ShareQQ(mContext).onSharePicAndText(funnys);
                DoLikeOr doLikeOr = new DoLikeOr() {
                    @Override
                    public void onSuccess(String msg) {
                        helper.setText(R.id.tv_xd_share, Integer.parseInt(funnys.shareCount) + 1 + "");
                        PreUtils.putBoolean(funnys.id + "share", true);
                    }

                    @Override
                    public void onDecodeError() {
                        UIUtils.showToast(mContext.getResources().getString(R.string.do_share_failed));
                    }
                };
                doLikeOr.sendRequest(funnys.id, funnys.userId, "SHARE");
            }
        });

        if ("GIF".equalsIgnoreCase(mediaType)) {
            CircleProgressView mCircleProgressView = helper.getView(R.id.iv_play);
            ImageView ivImg = helper.getView(R.id.iv_img);

            mCircleProgressView.setVisibility(View.VISIBLE);
            mCircleProgressView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    loadGifa(mContext, funnys.bigImage, helper.getView(R.id.iv_img), mCircleProgressView);
                }
            });

            ivImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //                    loadGifa(mContext, funnys.bigImage, helper.getView(R.id.iv_img), mCircleProgressView);
                    showPopupWindowRegist(funnys, "GIF");
                }
            });

        }

        if ("LIVE".equalsIgnoreCase(mediaType)) {

        }

        if ("IMAGE".equalsIgnoreCase(mediaType)) {
            ImageView ivImg = helper.getView(R.id.iv_img);
            ivImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showPopupWindowRegist(funnys, "IMAGE");
                }
            });
        }

    }

    public static void loadGifa(Context context, String imgUrl, ImageView iv, CircleProgressView mCircleProgressView) {
        GlideImageLoader imageLoader = new GlideImageLoader(iv);

        imageLoader.setOnGlideImageViewListener(imgUrl, new OnGlideImageViewListener() {
            @Override
            public void onProgress(int percent, boolean isDone, GlideException exception) {
                if (exception != null && !TextUtils.isEmpty(exception.getMessage())) {
                    UIUtils.showToast("~等等再试吧~");
                }
                mCircleProgressView.setProgress(percent);
                mCircleProgressView.setVisibility(isDone ? View.GONE : View.VISIBLE);
            }
        });

        RequestOptions options = imageLoader.requestOptions(R.color.placeholder_color)
                .centerCrop()
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
        ;

        RequestBuilder<Drawable> requestBuilder = imageLoader.requestBuilder(imgUrl, options);
        requestBuilder.transition(DrawableTransitionOptions.withCrossFade())
                .into(new SimpleTarget<Drawable>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        if (resource.getIntrinsicHeight() > DisplayUtil.getScreenHeight(context)) {
                            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        }
                        requestBuilder.into(iv);
                    }
                });
    }

    private RelativeLayout layout;
    private PopupWindow    popupWindow;

    public void showPopupWindowRegist(Funnys funnys, String type) {
        // 加载布局
        if ("GIF".equalsIgnoreCase(type)) {
            layout = (RelativeLayout) LayoutInflater.from(mContext).inflate(
                    R.layout.dialog_show_gif, null);
            popupWindow = new PopupWindow(layout, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
            ImageView iv_img = (ImageView) (layout).findViewById(R.id.iv_img);
            CircleProgressView mCircleProgressView = (CircleProgressView) (layout).findViewById(R.id.iv_play);
            GlideUtils.load(mContext, funnys.smallImage, iv_img);
            mCircleProgressView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    loadGifa(mContext, funnys.bigImage, iv_img, mCircleProgressView);
                }
            });
            iv_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupWindow.dismiss();
                }
            });
        }else if("LIVE_LIST".equalsIgnoreCase(type)){


        } else if ("IMAGE".equalsIgnoreCase(type)) {
            layout = (RelativeLayout) LayoutInflater.from(mContext).inflate(
                    R.layout.dialog_regist, null);
            popupWindow = new PopupWindow(layout, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
            //            ImageView iv_show = (ImageView) (layout).findViewById(R.id.iv_show);
            //            GlideUtils.load(mContext, funnys.bigImage, iv_show);
            SubsamplingScaleImageView iv_show = (SubsamplingScaleImageView) (layout).findViewById(R.id.iv_show);
            iv_show.setMinScale(1.0F);//最小显示比例
            iv_show.setMaxScale(10.0f);//最大显示比例
            //下载图片保存到本地
            //            Glide.with(mContext)
            //                    .load(funnys.bigImage)
            //                    .downloadOnly(new SimpleTarget<File>() {
            //                @Override
            //                public void onResourceReady(File resource, Transition<? super File> transition) {
            //                    iv_show.setImage(ImageSource.uri(Uri.fromFile(resource)), new ImageViewState(1.0F, new PointF(0, 0), 0));
            //                }
            //                    });

            Glide.with(mContext).asBitmap().load(funnys.bigImage).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    BigDecimal widthB = new BigDecimal(resource.getWidth());
                    BigDecimal heightB = new BigDecimal(resource.getHeight());
                    if (widthB.divide(heightB, 2, BigDecimal.ROUND_DOWN).compareTo(new BigDecimal(0.5)) > 0) {
                        iv_show.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CENTER_INSIDE);
                    } else {
                        iv_show.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CENTER_CROP);
                    }
                    iv_show.setImage(ImageSource.bitmap(resource), new ImageViewState(1.0F, new PointF(0, 0), 0));
                }
            });
            iv_show.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupWindow.dismiss();
                }
            });
        }
        TextView tv_pop_save = (TextView) (layout).findViewById(R.id.tv_pop_save);
        TextView tv_pop_share = (TextView) (layout).findViewById(R.id.tv_pop_share);

        // 找到布局的控件
        // 实例化popupWindow

        // 控制键盘是否可以获得焦点
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //		popupWindow.setBackgroundDrawable(new PaintDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        //		// 设置popupWindow弹出窗体的背景
        //		WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        // 监听

        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        tv_pop_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downloadImg(funnys);
                //                popupWindow.dismiss();
            }
        });
        tv_pop_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (PreUtils.getBoolean(funnys.id + "share", false)) {
                    UIUtils.showToast(mContext.getResources().getString(R.string.do_share_already));
                    return;
                }
                                ShareUtil.share(mContext, funnys);
                //                popupWindow.dismiss();
            }
        });
        popupWindow.showAsDropDown(tv_pop_save);
    }

    private void downloadImg(Funnys funnys) {
        String imgUrl = funnys.bigImage;
        requestRuntimePermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionListener() {
            @Override
            public void onGranted() {
                new DownloadImgTask(Integer.parseInt(funnys.id)).execute(imgUrl);
            }

            @Override
            public void onDenied(List<String> deniedPermissions) {
                UIUtils.showToast(mContext.getString(R.string.write_storage_permission_deny));
            }
        });


    }

    class DownloadImgTask extends AsyncTask<String, Integer, Void> {

        private int  mPosition;
        private File destFile;

        public DownloadImgTask(int position) {
            mPosition = position;
        }

        @Override
        protected Void doInBackground(String... params) {
            String imgUrl = params[0];
            File file = null;
            try {
                FutureTarget<File> future = Glide
                        .with(mContext)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                file = future.get();

                String filePath = file.getAbsolutePath();

                String destFileName = System.currentTimeMillis() + FileUtils.getImageFileExt(filePath);
                destFile = new File(FileUtils.getDir("shyFunny"), destFileName);

                FileUtils.copy(file, destFile);// 保存图片

                // 最后通知图库更新
                mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(new File(destFile.getPath()))));
            } catch (Exception e) {
                KLog.e(TAG, e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            UIUtils.showToast("保存成功，图片所在文件夹:" + destFile.getPath());
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            KLog.i(TAG, "progress: " + values[0]);
        }
    }

    /**
     * 申请运行时权限
     */
    public void requestRuntimePermission(String[] permissions, PermissionListener permissionListener) {
        mPermissionListener = permissionListener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions((Activity) mContext, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            permissionListener.onGranted();
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    List<String> deniedPermissions = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int grantResult = grantResults[i];
                        String permission = permissions[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            deniedPermissions.add(permission);
                        }
                    }
                    if (deniedPermissions.isEmpty()) {
                        mPermissionListener.onGranted();
                    } else {
                        mPermissionListener.onDenied(deniedPermissions);
                    }
                }
                break;
        }
    }
}
